package app.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import app.model.Application;
import app.model.Member;

/** 
 * 
 * @author Nachman Mathieu
 * @author David Gianorio
 * @author Faton Alia
 * 
 * This class contains all queries needed to get Application Objects */

@Repository
@Transactional
@SuppressWarnings("unchecked")
public class ApplicationDao {
	
	@PersistenceContext
	private EntityManager em;
	
	/** This method will list all applications created by a developer (sent in paramater) */
	public synchronized List<Application> getApplicationsByDeveloper(Member developer){
		
		List<Application> applicationListByDeveloper = (List<Application>)em.createQuery("SELECT a FROM Application a WHERE a.applicationCreator =: developerId")
		 .setParameter("developerId", developer.getId()).getResultList();
		
		if(applicationListByDeveloper.isEmpty()){
			throw new NoResultException("The list of applications is empty");
		} else {
			return applicationListByDeveloper;	
		}
	}
	
	/** This method will list the last uploaded applications */
	public synchronized List<Application> getLastUploadedApplications() {
		
		List<Application> lastUploadedApplicationsList = (List<Application>)em.createQuery("SELECT a FROM Application a ORDER BY a.appUploadDate DESC").setMaxResults(10).getResultList();
		
		if(lastUploadedApplicationsList.isEmpty()){
			throw new NoResultException("The list of applications is empty");
		} else {
			return lastUploadedApplicationsList;	
		}
	}
	
	/** This method will list the applications most downloaded */
	public synchronized List<Application> getTopApplication() {

		List<Application> topApplicationsList = (List<Application>)em.createQuery("SELECT a FROM Application a ORDER BY a.appNumberOfDownload DESC").setMaxResults(10).getResultList();
		
		if(topApplicationsList.isEmpty()){
			throw new NoResultException("The list of applications is empty");
		} else {
			return topApplicationsList;	
		}
	}
	
	/** This method will list all the applications in the DB */
	public synchronized List<Application> getAllApplications(){
		
		List<Application> allApplicationsList = (List<Application>)em.createQuery("SELECT a FROM Application a").setMaxResults(10).getResultList();
		
		if(allApplicationsList.isEmpty()){
			throw new NoResultException("The list of applications is empty");
		} else {
			return allApplicationsList;	
		}
	}
	
	public synchronized Object find(Long id){
		return em.find(Application.class, id);
	}

	public synchronized Object merge(Object obj){
		return em.merge(obj);
	}

	public synchronized void persist(Object obj){
		em.persist(obj);
	}
}